<template>
  <div class="app-main-box">

    <div class="func-btn">
      <el-button round type="default" plain icon="Back" @click="$router.go(-1)">返回</el-button>
    </div>

    <!-- 详情表单区域 -->
    <el-form class="form-content">
      <el-form-item label="对账单号：" prop="id" class="form-items" :style="`width: calc(${100 / formColumn}% - 48px)`">
        <span class="model-value" v-if="dataInfo.id">{{ dataInfo.id
          }}</span>
        <span class="model-value no-model-value" v-else>{{ '-' }}</span>
      </el-form-item>
      <el-form-item label="标题：" prop="title" class="form-items" :style="`width: calc(${100 / formColumn}% - 48px)`">
        <span class="model-value" v-if="dataInfo.title">{{ dataInfo.title
          }}</span>
        <span class="model-value no-model-value" v-else>{{ '-' }}</span>
      </el-form-item>
      <el-form-item label="总数：" prop="amount" class="form-items" :style="`width: calc(${100 / formColumn}% - 48px)`">
        <span class="model-value" v-if="dataInfo.amount">{{
          dataInfo.amount
        }}</span>
        <span class="model-value no-model-value" v-else>{{ '-' }}</span>
      </el-form-item>
      <el-form-item label="应收总金额：" prop="amountReceivable" class="form-items"
        :style="`width: calc(${100 / formColumn}% - 48px)`">
        <span class="model-value" v-if="dataInfo.amountReceivable">{{
          dataInfo.amountReceivable
        }}</span>
        <span class="model-value no-model-value" v-else>{{ '-' }}</span>
      </el-form-item>
      <el-form-item label="对账人：" prop="operatorName" class="form-items"
        :style="`width: calc(${100 / formColumn}% - 48px)`">
        <span class="model-value" v-if="dataInfo.operatorName">{{
          dataInfo.operatorName
        }}</span>
        <span class="model-value no-model-value" v-else>{{ '-' }}</span>
      </el-form-item>
      <el-form-item label="对账时间：" prop="createTime" class="form-items"
        :style="`width: calc(${(100 / formColumn)}% - 48px)`">
        <span class="model-value" v-if="dataInfo.createTime">{{ dataInfo.createTime }}</span>
        <span class="model-value no-model-value" v-else>{{ '-' }}</span>
      </el-form-item>
      <el-form-item label="备注：" prop="remark" class="form-items" :style="`width: calc(${100 / formColumn}% - 48px)`">
        <span class="model-value model-remark" v-if="dataInfo.remark">{{ dataInfo.remark }}</span>
        <span class="model-value no-model-value" v-else>{{ '-' }}</span>
      </el-form-item>
      <el-form-item prop="attachments" class="form-items" :style="`width: calc(${(100 / formColumn) * 2}% - 72px)`">
        <template #label>
          <span>附件<el-popover popper-class="custom-popper" placement="top" title="说明" :width="280"
              trigger="hover" :content="attachments_explain_content">
              <template #reference>
                <el-icon class="warning-icon">
                  <InfoFilled />
                </el-icon>
              </template>
            </el-popover>：</span>
        </template>
        <div class="file-list">
          <div class="file-container" v-for="(item, index) in dataInfo.attachments" :key="item.id">
            <div class="file-icon">
              <svg-icon :icon-class="getExtension(item.fileName)" style="width: 40px;height: 40px;" />
            </div>
            <!-- <p class="file-text">{{ item.fileName }}</p> -->
            <div class="file-text">
              <span>{{ item.fileName }}</span>
            </div>
            <div class="mask-containter">
              <span
                v-if="getExtension(item.fileName) == 'png' || getExtension(item.fileName) == 'jpg' || getExtension(item.fileName) == 'jpeg'"
                class="preview">
                <el-icon :size="20" @click="viewImage(item)">
                  <View />
                </el-icon>
              </span>
              <span v-else class="preview" @click="handlePreview(item)">
                <el-icon :size="20">
                  <View />
                </el-icon>
              </span>
              <span class="delete" @click="handleDelete(item, index)">
                <el-icon :size="20">
                  <Delete />
                </el-icon>
              </span>
            </div>
          </div>
          <el-upload v-if="dataInfo.attachments && dataInfo.attachments.length < 5" class="upload-demo"
            accept=".xls, .xlsx,.png,.jpg,.doc,.docx,.pdf,.jpeg" :on-change="handleChange" :auto-upload="false"
            :multiple="false">
            <div class="add-attachment">
              <el-icon :size="40">
                <Plus />
              </el-icon>
            </div>
          </el-upload>
        </div>
        <!-- <span class="model-value no-model-value" v-if="dataInfo.attachments">{{ '-' }}</span> -->
      </el-form-item>
    </el-form>

    <!-- 文件预览传送门 -->
    <teleport to="body">
      <div class="global-preview-file-container" v-if="show_frame_view">
        <IFrame :src="file_url" style="width: 100%; height: 100%"></IFrame>
        <span class="global-viewer-close" @click="closePreviewFile">
          <el-icon>
            <Close />
          </el-icon>
        </span>
      </div>
    </teleport>


    <div v-if="transportList.length" class="flex-space-between" style="padding: 0 24px;">
      <div class="global-title-bar">
        <div class="dot"></div>
        <div class="text">详细数据</div>
      </div>
      <div class="flex-right">
        <el-button round type="default" plain style="margin-bottom: 20px" icon="Download"
          @click="exportData">导出数据</el-button>
      </div>
    </div>


    <div v-if="transportList.length" class="global-table-container" style="margin-top: 20px;padding-bottom: 24px;"
      v-loading="loading">
      <vxe-table border align="center" show-overflow max-height="605" highlight-hover-row
        :scroll-y="{ enabled: true, gt: 0 }" :row-config="{ height: 35 }" :scroll-x="{ enabled: true, gt: 0 }"
        :data="transportList" :header-cell-style="grayColor">
        <vxe-column type="seq" width="70" header-class-name="start-front"></vxe-column>
        <!-- 车牌号 车辆来源 磅单号 箱号 线路 货物 发车时间 -->
        <vxe-colgroup title="发端" header-class-name="start-front">
          <vxe-column title="车牌号" field="originatingPlateNo" min-width="120"
            header-class-name="start-front"></vxe-column>
          <vxe-column title="磅单号" field="originatingWeightBillNo" min-width="180"
            header-class-name="start-front"></vxe-column>
          <vxe-column title="箱号" field="originatingContainerNo" min-width="120"
            header-class-name="start-front"></vxe-column>
          <vxe-column title="线路名称" field="originatingRouteName" min-width="120"
            header-class-name="start-front"></vxe-column>
          <vxe-column title="货物" field="originatingCargo" min-width="120" header-class-name="start-front"></vxe-column>
          <vxe-column title="发车时间" field="originatingDepartureTime" min-width="150"
            header-class-name="start-front"></vxe-column>
        </vxe-colgroup>
        <!-- 磅单号 车号 箱号 运单号  发站 到站 装车日期 -->
        <vxe-colgroup title="铁路" header-class-name="middle-front">
          <vxe-column title="磅单号" field="railwayWeightBillNo" min-width="180"
            header-class-name="middle-front"></vxe-column>
          <vxe-column title="车号" field="railwayTrainNo" min-width="120" header-class-name="middle-front"></vxe-column>
          <vxe-column title="箱号" field="railwayContainerNo" min-width="120"
            header-class-name="middle-front"></vxe-column>
          <vxe-column title="运单号" field="railwayBillNo" min-width="180" header-class-name="middle-front"></vxe-column>
          <vxe-column title="发站" field="railwayDepartureStation" min-width="120"
            header-class-name="middle-front"></vxe-column>
          <vxe-column title="到站" field="railwayArrivalStation" min-width="120"
            header-class-name="middle-front"></vxe-column>
          <vxe-column title="装车日期" field="railwayLoadingDate" min-width="150"
            header-class-name="middle-front"></vxe-column>
        </vxe-colgroup>
        <!-- 车牌号 磅单号 箱号  过磅日期   -->
        <vxe-colgroup title="到端">
          <vxe-column title="车牌号" field="receiptPlateNo" min-width="120"></vxe-column>
          <vxe-column title="磅单号" field="receiptWeightBillNo" min-width="180"></vxe-column>
          <vxe-column title="箱号" field="receiptContainerNo" min-width="120"></vxe-column>
          <vxe-column title="过磅日期" field="receiptWeightingDate" min-width="120"></vxe-column>
        </vxe-colgroup>
      </vxe-table>
    </div>

    <el-image-viewer v-if="showImagePreview" @close="closePreview" :url-list="imgPreviewList" hide-on-click-modal
      preview-teleported />

    <!-- 页码控件 -->
    <!-- <pagination v-show="false" :total="total" v-model:page="queryParams.pageIndex" v-model:limit="queryParams.pageSize"
      @pagination="getList" /> -->
  </div>
</template>

<script setup name="transportOrderList">
import IFrame from '@/components/iFrame'
import { ElMessage } from 'element-plus'
import { listTransPortApi, transportInfoApi, getWeightbillInfoApi, checkHaulApi, updateHaulApi } from "@/api/transportOrderManagement/transportOrderList";
import { getReconciliationInfoApi, addAttachmentApi, deleteAttachmentApi } from "@/api/financeManagement/upstreamReconciliation/railwayReconciliationInfo";
import { downloadApi } from "@/api/financeManagement/upstreamReconciliation/initiateReconciliation";
import { getRouteSimpleListApi } from "@/api/common";
import { reactive } from 'vue'
import { Plus } from '@element-plus/icons-vue';
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
let loading = ref(false);
let total = ref(0);
let transportList = ref([]) // 发端短驳
let formColumn = ref(3) // 每行展示3列
let file_url = ref('') // 文件预览地址
let show_frame_view = ref(false) // 文件预览地址
let current_file_list = ref([])
let fileList = ref([]) // 当前所选文件数组
let current_file = ref({}) // 当前所选文件
let showImagePreview = ref(false)
let imgPreviewList = ref([])
let attachments_explain_content = ref('支持格式xls,xlsx,pdf,png,jpg,jpeg, 文件大小不得大于10M,最多支持上传5个附件。')
/** 列表查询参数 */
const data = reactive({
  dataInfo: {
  },
  // queryParams: {
  //   pageIndex: 1,
  //   pageSize: 1000,
  // }
});
const { dataInfo } = toRefs(data);


/** 表头样式 */
const grayColor = ({ column }) => {
  if (column.headerClassName == 'start-front') {
    return {
      backgroundColor: '#f2f4f7 !important',
      color: '#515a6e',
      textAlign: 'center',
      height: '40px !important'
    }
  }
  else if (column.headerClassName == 'middle-front') {
    return {
      backgroundColor: '#e1f3d8 !important',
      color: '#515a6e',
      textAlign: 'center',
      height: '40px !important'
    }
  } else {
    return {
      backgroundColor: '#ecf5ff !important',
      color: '#515a6e',
      textAlign: 'center',
      height: '40px !important'
    }
  }
}


/** 
* Methods
*/
/** 查询 */
// function getList() {
//   loading.value = true;
//   const { routeId, isChecked, ...rest } = queryParams.value
//   let params = rest
//   isChecked != 'all' ? params["isChecked"] = isChecked : null
//   routeId != 'all' ? params["routeId"] = routeId : null
//   listTransPortApi(proxy.addDateRange(params, dateRange.value)).then(response => {
//     transportList = response.data.records;
//     total.value = Number(response.data.total);
//     loading.value = false;
//   }).catch(err => {
//     loading.value = false;
//   })
// }

/** 导出数据 */
/** 下载对账单API */
async function exportData() {
  downloadApi({ reconciliationId: route.query.id }).then((response) => {
    console.log(response, '文件');
    // const disposition = response.headers['content-disposition'];
    // const matchArray = disposition.match(/filename="(.*)"/);
    // const filename = matchArray[1];
    let filename = dataInfo.value.title + '.xlsx'
    const url = window.URL.createObjectURL(response);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click()
    document.body.removeChild(link); // 下载完成后移除元素
    window.URL.revokeObjectURL(url); // 释放URL对象
  })
}


/** 预览图片 */
async function viewImage(row) {
  showImagePreview.value = true
  imgPreviewList.value = [row.url]
}

function closePreview() {
  showImagePreview.value = false
  imgPreviewList.value = []
}

/** 文件状态变化 */
async function handleChange(file, fileList) {
  current_file.value = file.raw || file.file
  // 获取最新的文件
  const latestFile = file.raw || file.file;
  // 将最新的文件加入到fileList中
  fileList.value = [latestFile];
  /** 支持文件类型 */
  let supposeType = ['xls', 'xlsx', 'xlsx', 'jpg', 'pdf', 'png', 'jpeg']
  /** 获取文件后缀名 */
  if (supposeType.includes(getExtension(current_file.value.name))) {
    await addAttachment()
  } else {
    ElMessage({ message: '文件类型暂不支持，请重新上传', type: 'error', duration: 2000 })
  }
}

/** 添加附件接口 */
async function addAttachment() {
  let formData = new FormData();
  formData.append("file", current_file.value);
  formData.append("reconciliationId", route.query.id);
  await addAttachmentApi(formData).then((response) => {
    if (response.code === 1) {
      // 接口调用成功之后将返回的内容push进文件列表
      dataInfo.value.attachments.push(response.data)
    }
    else {
      ElMessage({ message: response.message, type: 'error', duration: 2000 })
    }
  })
  // 上传之后清空当前选择的文件列表
  current_file.value = {}
  fileList.value = []
}

/** 删除附件接口 */
function handleDelete(item, index) {
  proxy.$modal.confirm('是否确认删除该附件?').then(function () {
  }).then(() => {
    // 接口调用成功之后
    let params = {
      reconciliationId: route.query.id,
      fileId: item.id
    }
    deleteAttachmentApi(params).then((response) => {
      if (response.code === 1) {
        dataInfo.value.attachments.splice(index, 1)
        // proxy.$modal.msgSuccess("删除成功");
      } else {
        ElMessage({ message: response.message, type: 'error', duration: 2000 })
      }
    })
  }).catch(() => { });
}

/** 铁路发运对账单详情 */
function getReconciliationInfo() {
  loading.value = true
  getReconciliationInfoApi(route.query.id).then((response) => {
    if (response.code === 1) {
      const { waybillDataList, ...rest } = response.data
      console.log(rest, '详细数据');
      dataInfo.value = rest
      transportList.value = waybillDataList;
      loading.value = false
    } else {
      loading.value = false
    }
  })
}

/** 关闭iframe文件预览按钮 */
function closePreviewFile() {
  show_frame_view.value = false
}

/** 预览文件 */
async function handlePreview(item) {
  show_frame_view.value = true
  if (getExtension(item.url) == 'docx' || getExtension(item.url) == 'doc') {
    file_url.value = `https://view.xdocin.com/view?src=${item.url}`
  } else if (getExtension(item.url) == 'csv' || getExtension(item.url) == 'xls' || getExtension(item.url) == 'xlsx') {
    file_url.value = `https://view.officeapps.live.com/op/view.aspx?src=${item.url}`
  } else {
    file_url.value = item.url
  }
}

/** 获取文件后缀名 */
function getExtension(filename) {
  if (filename) {
    return filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2).toLowerCase();
  }
}

/** 文件名占位 */
// function getFileNamePlace(filename) {
//   let str = filename
//   let lastIndex = str.lastIndexOf('.');
//   str = str.substring(0, lastIndex);
//   if (str.slice(0, 18).length > 15) {
//     str = str.slice(0, 12) + '.' + getExtension(filename) + '...'
//   } else {
//     str = str.slice(0, 12) + '.' + getExtension(filename)
//   }
//   return str
// }

/** 搜索按钮操作 */
// function handleQuery() {
//   queryParams.value.pageIndex = 1;
//   getList();
// }

/** 重置按钮操作 */
// function resetQuery() {
//   dateRange.value = [];
//   queryParams.value.routeId = 'all'
//   queryParams.value.isChecked = 'all'
//   proxy.resetForm("queryRef");
//   handleQuery();
// }

// getList();
getReconciliationInfo()
</script>

<style lang='scss' scoped>
@import '../../../../assets/styles/variables.module.scss';

.app-main-box {
  background: #fff;
  border-radius: 12px;
  min-height: calc(100vh - 125px);
  width: calc(100% - 40px);
}

.flex-space-between {
  width: calc(100% - 48px) !important;
  display: flex;
  align-items: center;

  .flex-right {
    flex: 1;
    justify-self: flex-end !important;
    text-align: right;

    .el-button {
      margin: 0 !important;
    }
  }
}


/** 功能按钮 */
.func-btn {
  padding: 24px 24px 0px;
}

.form-content {
  display: flex;
  grid-gap: 10px 24px;
  flex-wrap: wrap !important;
  padding: 0px 24px;
  margin-top: 30px;

  .form-items {
    min-width: 210px;
  }
}

.model-value {
  display: inline-block;
  line-height: 1.5;
  width: 100%;
  color: $--color-info;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.model-remark {
  line-height: 1.5;
  word-wrap: break-word !important;
  white-space: normal !important;
  display: -webkit-box !important;
  -webkit-box-orient: vertical !important;
  /* 子元素排列垂直排列 */
  -webkit-line-clamp: 5 !important;
  /* 设置从第几行后开始省略 */
  overflow: hidden;
}

.file-list {
  display: flex;
  flex-wrap: wrap;
  border-radius: 4px;
  background-color: $--color-bg-info;
  overflow: hidden !important;

  &> :not(:last-child) {
    // margin-right: 20px !important;
    // margin-bottom: 20px !important;
  }

  .file-container {
    width: 120px;
    height: 120px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;

    .file-text {
      width: 80%;
      font-size: 12px;
      height: max-content;
      line-height: 16px;
      min-height: 32px;
      color: $--color-info;
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: center;
      font-feature-settings: "tnum";

      span {
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        // font-feature-settings: "tnum";
        font-feature-settings: "c2sc", "smcp";
      }
    }


  }

  .mask-containter {
    width: 120px;
    height: 120px;
    display: flex;
    grid-gap: 20px;
    align-items: center;
    justify-content: center;
    background-color: rgba(0, 0, 0, .5);
    position: absolute;
    opacity: 0;
    color: #fff;
  }

  .mask-containter:hover {
    opacity: 1;
  }

  .file-container:nth-of-type(1) {
    .mask-containter {
      border-top-left-radius: 4px;
      border-bottom-left-radius: 4px;
    }
  }

  .file-container:nth-of-type(5) {
    .mask-containter {
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
    }
  }



  .upload-demo {
    .add-attachment {
      width: 120px;
      height: 120px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: $--color-info;
      cursor: pointer;
      vertical-align: middle;
    }

    // 隐藏上upload传文件附件链接
    :deep(.el-upload-list) {
      display: none !important;
    }
  }


}

.global-table-container {
  padding: 0px 24px;
}

:deep(.el-form-item__content) {
  align-items: flex-start !important;
}

:deep(.el-form-item__label) {
  line-height: 1.5;
}

:deep(.warning-icon) {
  color: $--color-warning;
  font-size: 16px;
  vertical-align: text-top;
  margin-left: 2px;
  cursor: pointer;
}

// 媒介查询附件区域
@media screen and (min-width: 720px) {

  // 当屏幕宽度大于等于 720px 时应用的样式
  .file-list {
    width: 240px;
    max-width: max-content !important;
    overflow: hidden !important;
  }
}

@media screen and (min-width: 920px) {
  .file-list {
    width: 360px;
    max-width: max-content !important;
    overflow: hidden !important;
  }
}

@media screen and (min-width: 1240px) {
  .file-list {
    width: 480px;
    max-width: max-content !important;
    overflow: hidden !important;
  }
}

@media screen and (min-width: 1480px) {
  .file-list {
    width: 720px;
    max-width: max-content !important;
    overflow: hidden !important;
  }
}
</style>